<template>
  <el-dialog
    v-model="visible"
    :title="`配置任务 - ${stream?.name || ''}`"
    width="520px"
    @close="handleClose"
    class="task-config-dialog compact ultra-compact"
  >
    <!-- 流状态提示 - 合并为一行 -->
    <el-alert
      v-if="stream?.status !== 'active'"
      title="当前流未启动，配置的任务将在流启动后自动执行"
      type="info"
      show-icon
      :closable="false"
      class="stream-status-alert ultra-compact"
    />
    
    <div class="task-config-container ultra-compact">
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="100px"
        class="task-form ultra-compact"
        size="small"
      >
        <!-- 录制任务配置 -->
        <div class="task-section ultra-compact">
          <div class="section-header ultra-compact">
            <i class="section-icon ultra-compact">🎬</i>
            <span>录制任务</span>
            <el-tag v-if="recordTaskExists" type="success" size="small" style="margin-left: 6px; font-size: 11px; padding: 1px 4px; height: 16px; line-height: 14px;">已配置</el-tag>
          </div>
          <el-form-item label="录制任务" class="compact-item">
            <el-switch
              v-model="taskForm.record_enabled"
              :disabled="recordTaskExists"
              active-text="启用"
              inactive-text="关闭"
              size="small"
            />
            <div v-if="recordTaskExists" class="info-text ultra-compact" style="margin-top: 4px; color: #67c23a;">
              该直播录制任务已存在，无需重复创建
            </div>
          </el-form-item>

          <template v-if="taskForm.record_enabled">
            <el-form-item label="录制文件路径" class="compact-item">
              <div class="path-input-group ultra-compact">
                <el-input
                  :value="recordFilePath"
                  readonly
                  class="readonly-input ultra-compact"
                  size="small"
                >
                  <template #suffix>
                    <el-button 
                      size="small" 
                      type="primary" 
                      text 
                      @click="copyToClipboard(recordFilePath)"
                      class="copy-btn ultra-compact"
                    >
                      📋
                    </el-button>
                  </template>
                </el-input>
                <div class="info-text ultra-compact">
                  文件将自动保存到上述路径，分辨率为原视频尺寸，格式为TS。<br>如需其他格式，请在录制管理中进行转码
                </div>
              </div>
            </el-form-item>
          </template>
        </div>

        <!-- 转推任务配置 -->
        <div class="task-section ultra-compact">
          <div class="section-header ultra-compact">
            <i class="section-icon ultra-compact">🔄</i>
            <span>转推任务</span>
          </div>
          <el-form-item label="转推任务" class="compact-item">
            <el-switch
              v-model="taskForm.relay_enabled"
              active-text="启用"
              inactive-text="关闭"
              size="small"
            />
          </el-form-item>

          <template v-if="taskForm.relay_enabled">
            <el-form-item label="转推地址" prop="relay_url" class="compact-item">
              <el-input
                v-model="taskForm.relay_url"
                placeholder="请输入RTMP转推地址"
                class="url-input ultra-compact"
                size="small"
              />
            </el-form-item>
          </template>
        </div>

        <!-- 转码任务配置 -->
        <div class="task-section ultra-compact">
          <div class="section-header ultra-compact">
            <i class="section-icon ultra-compact">⚙️</i>
            <span>转码任务</span>
          </div>
          <el-form-item label="转码任务" class="compact-item">
            <el-switch
              v-model="taskForm.transcode_enabled"
              active-text="启用"
              inactive-text="关闭"
              size="small"
            />
          </el-form-item>

          <template v-if="taskForm.transcode_enabled">
            <el-form-item label="转码模板" prop="transcode_template_id" class="compact-item">
              <el-select 
                v-model="taskForm.transcode_template_id" 
                placeholder="请选择转码模板"
                filterable
                class="template-select ultra-compact"
                size="small"
              >
                <el-option
                  v-for="template in transcodeTemplates"
                  :key="template.id"
                  :label="template.name"
                  :value="template.id"
                  class="template-option ultra-compact"
                >
                  <div class="template-info ultra-compact">
                    <span class="template-name">{{ template.name }}</span>
                    <span class="template-specs">{{ template.resolution }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="转码推流地址" v-if="taskForm.transcode_template_id" class="compact-item">
              <div class="url-display-group ultra-compact">
                <el-input
                  :value="transcodeRtmpUrl"
                  readonly
                  class="readonly-input ultra-compact"
                  size="small"
                >
                  <template #prefix>
                    <span class="url-label ultra-compact">RTMP:</span>
                  </template>
                  <template #suffix>
                    <el-button 
                      size="small" 
                      type="primary" 
                      text 
                      @click="copyToClipboard(transcodeRtmpUrl)"
                      class="copy-btn ultra-compact"
                    >
                      📋
                    </el-button>
                  </template>
                </el-input>
                <el-input
                  :value="transcodeHlsUrl"
                  readonly
                  class="readonly-input ultra-compact"
                  size="small"
                >
                  <template #prefix>
                    <span class="url-label ultra-compact">HLS:</span>
                  </template>
                  <template #suffix>
                    <el-button 
                      size="small" 
                      type="primary" 
                      text 
                      @click="copyToClipboard(transcodeHlsUrl)"
                      class="copy-btn ultra-compact"
                    >
                      📋
                    </el-button>
                  </template>
                </el-input>
                <div class="info-text ultra-compact">
                  转码后将自动生成推流地址，可直接使用
                </div>
              </div>
            </el-form-item>
          </template>
        </div>


      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer ultra-compact">
        <el-button @click="handleClose" size="small">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="loading"
          size="small"
        >
          {{ loading ? '配置中...' : '确认配置' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import taskApi from '@/api/task'
import transcodeApi from '@/api/transcode'

// Props and Emits
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  stream: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

// Reactive data
const visible = ref(false)
const loading = ref(false)
const transcodeTemplates = ref([])
const showResult = ref(false)
const taskFormRef = ref()
const recordTaskExists = ref(false)
const relayTaskExists = ref(false)
const transcodeTaskExists = ref(false)

const taskForm = reactive({
  record_enabled: false,
  record_format: 'ts', // 固定为TS
  relay_enabled: false,
  relay_url: '',
  transcode_enabled: false,
  transcode_template_id: null,
  
})

const taskRules = {
  relay_url: [
    { required: true, message: '请输入转推地址', trigger: 'blur' },
    { type: 'url', message: '请输入有效的RTMP地址', trigger: 'blur' }
  ],
  transcode_template_id: [
    { required: true, message: '请选择转码模板', trigger: 'change' }
  ]
}

// Computed properties
const recordFilePath = computed(() => {
  if (!props.stream) return ''
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  
  return `文件存储/recording/${props.stream.id}_record_${year}${month}${day}${hour}${minute}/`
})

const transcodeRtmpUrl = computed(() => {
  if (!props.stream || !taskForm.transcode_template_id) return ''
  const baseUrl = window.location.hostname
  return `rtmp://${baseUrl}:1935/live/${props.stream.id}_${taskForm.transcode_template_id}`
})

const transcodeHlsUrl = computed(() => {
  if (!props.stream || !taskForm.transcode_template_id) return ''
  const baseUrl = window.location.hostname
  return `http://${baseUrl}:8080/live/${props.stream.id}.m3u8`
})

// 移除旧的计算属性
// const recordUrl = computed(() => {...})
// const relayRtmpUrl = computed(() => {...})
// const relayHlsUrl = computed(() => {...})
// const transcodeOutputUrl = computed(() => {...})

// Watch for dialog visibility
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    loadTranscodeTemplates()
    checkExistingTasks()
    resetForm()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// Methods
const checkExistingTasks = async () => {
  if (!props.stream) return
  
  try {
    const response = await taskApi.getTasks({
      stream_id: props.stream.id
    })
    
    if (response?.items) {
      const tasks = response.items
      recordTaskExists.value = tasks.some(task => task.task_type.includes('record'))
      relayTaskExists.value = tasks.some(task => task.task_type.includes('push'))
      transcodeTaskExists.value = tasks.some(task => task.task_type.includes('transcode'))
      
      // 如果已有录制任务，自动勾选并禁用录制开关
      if (recordTaskExists.value) {
        taskForm.record_enabled = true
      }
    }
  } catch (error) {
    console.error('检查现有任务失败:', error)
  }
}

const loadTranscodeTemplates = async () => {
  try {
    const response = await transcodeApi.getTranscodeTemplates()
    console.log('转码模板响应:', response)
    
    // API拦截器已处理外层格式，直接返回data内容：{items: [...], total: ...}
    if (response?.items && Array.isArray(response.items)) {
      transcodeTemplates.value = response.items
      console.log('加载的转码模板:', transcodeTemplates.value)
    } else {
      console.error('转码模板数据格式错误:', response)
      transcodeTemplates.value = []
    }
  } catch (error) {
    console.error('获取转码模板失败:', error)
    ElMessage.error('获取转码模板失败: ' + (error.response?.data?.detail || error.message))
    transcodeTemplates.value = []
  }
}

const resetForm = () => {
  // 重置表单时，如果已有任务则保持勾选状态
  taskForm.record_enabled = recordTaskExists.value
  taskForm.record_format = 'ts' // 固定为TS
  taskForm.relay_enabled = false
  taskForm.relay_url = ''
  taskForm.transcode_enabled = false
  taskForm.transcode_template_id = null
  
}

const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (error) {
    // Fallback for older browsers
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('复制成功')
  }
}

const handleClose = () => {
  visible.value = false
  showResult.value = false
}

const handleSubmit = async () => {
  if (!props.stream) return
  
  try {
    await taskFormRef.value.validate()
    loading.value = true
    
    // 收集所有选中的任务类型
    const selectedTypes = []
    const requestData = {
      stream_id: props.stream.id
    }
    
    if (taskForm.record_enabled) {
      selectedTypes.push('record')
      requestData.record_path = `文件存储/直播录制/${props.stream.name}_record_${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}${String(new Date().getHours()).padStart(2, '0')}${String(new Date().getMinutes()).padStart(2, '0')}/`
    }
    
    if (taskForm.transcode_enabled && taskForm.transcode_template_id) {
      selectedTypes.push('transcode')
      requestData.tempid = String(taskForm.transcode_template_id)
      const baseUrl = window.location.hostname
      requestData.transcode_url = `rtmp://${baseUrl}:1935/live/${props.stream.id}_${taskForm.transcode_template_id};http://${baseUrl}:8080/live/${props.stream.id}.m3u8`
    }
    
    if (taskForm.relay_enabled) {
      selectedTypes.push('push')
      requestData.push_url = taskForm.relay_url
    }
    
    if (selectedTypes.length === 0) {
      ElMessage.warning('请至少选择一个任务类型')
      return
    }
    
    // 构建任务类型字符串和名称
    const taskTypeString = selectedTypes.join('_')
    requestData.task_type = taskTypeString
    requestData.name = `${props.stream.name}_${props.stream.id}_${taskTypeString}`
    
    // 创建任务
    await taskApi.createTask(requestData)
    
    ElMessage.success('任务配置成功')
    handleClose()
    emit('success')
    
  } catch (error) {
    console.error('创建任务失败:', error)
    ElMessage.error('创建任务失败')
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
.task-config-dialog.compact.ultra-compact {
  --el-dialog-border-radius: 6px;
}

.stream-status-alert.ultra-compact {
  margin-bottom: 8px;
  padding: 6px 10px;
  font-size: 13px; /* 从12px增大到13px */
}

.task-config-container.ultra-compact {
  padding: 2px 0;
}

.task-form.ultra-compact {
  margin: 0;
}

.task-section.ultra-compact {
  margin-bottom: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.section-header.ultra-compact {
  margin-bottom: 8px;
  padding-bottom: 4px;
}

.section-icon.ultra-compact {
  font-size: 14px;
  margin-right: 4px;
}

.section-header.ultra-compact span {
  font-size: 15px; /* 从14px增大到15px */
  font-weight: 600;
}

:deep(.ultra-compact .el-form-item) {
  margin-bottom: 8px;
}

:deep(.ultra-compact .el-form-item__label) {
  font-size: 13px; /* 从12px增大到13px */
  font-weight: 500;
  padding-right: 6px;
}

:deep(.compact-item) {
  margin-bottom: 6px !important;
}

:deep(.ultra-compact .el-switch) {
  transform: scale(0.9); /* 从0.85调整到0.9 */
}

:deep(.ultra-compact .el-switch__label) {
  font-size: 13px; /* 从12px增大到13px */
}

.path-input-group.ultra-compact,
.url-display-group.ultra-compact {
  width: 100%;
}

.readonly-input.ultra-compact {
  margin-bottom: 2px;
}

:deep(.ultra-compact .readonly-input .el-input__wrapper) {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 3px 8px; /* 从2px6px增大到3px8px */
}

:deep(.ultra-compact .readonly-input .el-input__inner) {
  font-size: 13px; /* 从12px增大到13px */
  line-height: 1.4;
}

.url-label.ultra-compact {
  font-size: 11px; /* 从10px增大到11px */
  margin-right: 2px;
}

.copy-btn.ultra-compact {
  font-size: 11px; /* 从10px增大到11px */
  padding: 2px 4px; /* 从1px2px增大到2px4px */
  min-height: 18px; /* 从16px增大到18px */
}

.url-input.ultra-compact,
.template-select.ultra-compact {
  width: 100%;
}

:deep(.ultra-compact .url-input .el-input__wrapper),
:deep(.ultra-compact .template-select .el-input__wrapper) {
  border-radius: 4px;
  padding: 3px 8px; /* 从2px6px增大到3px8px */
}

.template-info.ultra-compact {
  font-size: 13px; /* 从12px增大到13px */
}

.template-specs {
  font-size: 11px; /* 从10px增大到11px */
}

.info-text.ultra-compact {
  margin-top: 3px; /* 从2px增大到3px */
  font-size: 12px; /* 从11px增大到12px */
  line-height: 1.4;
  padding: 5px 8px; /* 从4px6px增大到5px8px */
  border-radius: 3px;
  border-left: 1px solid #409eff;
}

.dialog-footer.ultra-compact {
  gap: 6px;
}

:deep(.ultra-compact .el-dialog__body) {
  padding: 10px 14px; /* 从8px12px增大到10px14px */
}

:deep(.ultra-compact .el-dialog__header) {
  padding: 10px 14px; /* 从8px12px增大到10px14px */
  /* 标题大小保持不变 */
}

:deep(.ultra-compact .el-dialog__title) {
  /* 标题大小保持不变 */
  font-size: 15px;
}

:deep(.ultra-compact .el-dialog__close) {
  font-size: 14px;
}

:deep(.ultra-compact .el-button--small) {
  padding: 5px 10px; /* 从4px8px增大到5px10px */
  font-size: 13px; /* 从12px增大到13px */
}

@media (max-width: 768px) {
  .task-config-dialog.compact.ultra-compact {
    width: 98vw !important;
  }
  
  .task-section.ultra-compact {
    padding: 8px 10px; /* 从6px8px增大到8px10px */
    margin-bottom: 8px;
  }
  
  :deep(.ultra-compact .el-form-item__label) {
    font-size: 13px; /* 从11px增大到13px */
  }
}
</style>